﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.OrmLite;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite.Dapper;

namespace LCRReader
{
    public class portconfig
    {
        public string Name { get; set; }
        public string COM { get; set; }
        public int Baudrate { get; set; }
        public int DataBits { get; set; }
        public string Stopbits { get; set; }
        public string Parity { get; set; }
    }
    public class portconfigAccess
    {
        static string _path = "";
        static System.Data.IDbConnection _db = null;
        public portconfigAccess(string path = "./config/cfg.db")
        {
            if (path != _path)
            {
                _path = path;
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path)))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
                }
                OrmLiteConnectionFactory con = new OrmLiteConnectionFactory(path, SqliteDialect.Provider);

                _db = con.Open();
                if (!_db.TableExists<portconfig>())
                {
                    _db.DropAndCreateTable<portconfig>();
                    _db.Insert(new portconfig() { Baudrate = 9600, COM = "COM1", DataBits = 8, Name = "LCR", Parity = "NONE", Stopbits = "1" });
                }
            }
        }

        public portconfig GetportConfigByName(string Name = "LCR")
        {
            var qs = _db.Select<portconfig>(t => t.Name == Name);
            if (qs != null && qs.Count > 0)
            {
                return qs[0];
            }
            else
            {
                return new portconfig()
                { Baudrate = 9600, Name = "LCR", COM = "COM1", DataBits = 8, Parity = "NONE", Stopbits = "1" };
            }
        }
        public int UpdataConfigByName(portconfig portconfig, string Name = "LCR")
        {
           return _db.Update(portconfig, t => t.Name == Name);     
        }
    }
}
